package search.impl;

import search.SymbolTable;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class TextIndex implements search.text.TextIndex {
    private SymbolTable<String, List<Integer>> table;
    private int[] amount;

    public TextIndex(SymbolTable<String, List<Integer>> table, int[] amount) {
        this.table = table;
        this.amount = amount;
    }

    public void buildIndex(String text) throws Exception {
        List<String> words = getWords(text);
        int place = 0;
        for (String word : words) {
            if (table.containsKey(word)) {
                table.get(word).add(place);
            } else {
                List<Integer> positions = new LinkedList<Integer>();
                positions.add(place);
                table.put(word, positions);
            }
            place++;
        }
    }

    private List<String> getWords(String text) {
        int cont = 0;
        List<String> words = new ArrayList<String>();
        try {
            FileReader reader = new FileReader(text);
            int character = reader.read();
            String word = "";
            while (character != -1) {
                if (cont == amount[0]) break;
                while ((character >= 65 && character <= 90) || (character >= 97 && character <= 122)) {
                    word += (char) character;
                    character = reader.read();
                }
                if (word.length() != 0) {
                    words.add(word.toLowerCase());
                    cont++;
                    word = "";
                }
                character = reader.read();
            }
            System.out.println("****La cantidad de palabras son: " + cont + "****");
            reader.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return words;
    }

    public List<Integer> search(String word) throws Exception {
        return table.get(word);
    }


}
